package simtester.test

import static org.junit.Assert.*

import com.gmongo.GMongo
import geb.junit4.GebReportingTest
import org.junit.After
import org.junit.AfterClass
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import simtester.test.pages.*
import simtester.test.Utils

class UserTests extends GebReportingTest {
    static def testConfig
    static def db
    
    @BeforeClass
    static void setUpAll() {
        testConfig = new ConfigSlurper().parse(new File('grails-app/conf/SimTesterConfig.groovy').toURI().toURL())
        db = new GMongo().getDB(testConfig.test.dbname)
        
        Utils.dropCollections(db)
        
        // Create team Unassigned if not exist
        def team = db.team.findOne(name: 'unassigned')
        if (!team) {
            db.team << [_id: 2L, name: 'unassigned', version: 1L]
        }
    }
    
    @AfterClass
    static void tearDownAll() {
        Utils.dropCollections(db)
    }

    @Before
    void setUp() {
    }

    @After
    void tearDown() {
        //db.instance.remove([:])
        //db.user.remove([:])
        //db.testCase.remove([:])
        //db.team.remove([:])
        def dirs = new File(testConfig.test.env).listFiles()
        dirs.each {
            new AntBuilder().delete(dir: it)
        }
    }
    
    @Test
    void createUser() {
        to LoginPage
        assert at(LoginPage)
        $('a', name: 'register').click(RegisterPage)
        
        assert at(RegisterPage)
        def testusername = 'testuser'
        registerUser(username: testusername)

        assert at(HomePage)
        assert $('div.message').text() == "User $testusername created successfully!"
        
        def user = db.user.find(username: testusername)
        assert user.count() == 1
    }
    
    @Test
    void createUserWithError() {
        to RegisterPage
        assert at(RegisterPage)
        
        def testusername = 'testuser2'
        registerUser(username: testusername)
        
        assert at(HomePage)
        
        // Create user that already exists
        to RegisterPage
        assert at(RegisterPage)
        registerUser(username: testusername)
        
        assert at(RegisterPage)
        assert $('div p.error').text() == "username \"$testusername\" already exists"
    }
    
    @Test
    void createUserWithPwConfirmationMismatch() {
        to RegisterPage
        assert at(RegisterPage)
        
        def testusername = 'testuser'
        registerUser(username: testusername, password_confirmation: 'pw')
        
        assert at(RegisterPage)
        assert $('div p.error').text() == 'Passwords do not match'
    }

}
